package com.webserver.servlet;

import com.webserver.controllers.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 *  用于处理请求的Servlet
 *  ClientHandler处理请求的环节调用当前类的service方法完成处理细节
 */
public class DispatcherServlet {
    public void service(HttpRequest request, HttpResponse response) {
        //通过request获取抽象路径中的请求部分
        String path = request.getRequestURI();//获取抽象路径
        System.out.println("请求路径========> " + path);

        //首先判断是否为请求一个业务
        if ("/myweb/regUser".equals(path)) {
            //如果是请求注册业务,就处理注册
            UserController servlet = new UserController();
            servlet.reg(request, response);
        } else if("/myweb/loginUser".equals(path)) {
            UserController servlet = new UserController();
            servlet.login(request,response);
        }else if ("/myweb/createArticleUser".equals(path)) {
            UserController servlet = new UserController();
            servlet.create(request,response);
        }else if ("/myweb/showAllUser".equals(path)) {
            UserController servlet = new UserController();
            servlet.userList(request,response);
        }else if ("/myweb/deleteUser".equals(path)) {
            UserController servlet = new UserController();
            servlet.delete(request,response);
        }else if ("/myweb/showAllArticle".equals(path)) {
            UserController servlet = new UserController();
            servlet.articleList(request,response);
        }else {
            File file = new File("./webapps" + path);
            if (file.exists() && file.isFile()) {//是否存在
                response.setEntity(file);
            } else {
//                File notFoundPage = new File("./webapps/root/404.html");
//                response.setStatusCode(404);
//                response.setStatusReason("NotFound");
//                response.setEntity(notFoundPage);

                //重定向到/root/404.html
                /*
                     这里定位root下的404.html时指定的相对目录也是让浏览器理解的
                     例:
                        浏览器请求路径:
                        http://localhost:8088/myweb/123123(不存在的地址)

                        如果浏览器此时接收到的响应中有相对路径,浏览器理解的路径对应为:
                        当前目录,"./"  :http://localhost:8088/myweb/a/
                        根目录,  "/"   :http://localhost:8088/
                        上级目录,"../" :http://localhost:8088/myweb/
                 */
                response.sendRedirect("/root/404.html");
            }
        }
        //设置通用响应头
        response.addHeader("Server", "WebServer");
    }
}